//
//  FGHomeViewController.swift
//  飞哥大微博
//
//  Created by huangfei on 2017/6/1.
//  Copyright © 2017年 huangfei. All rights reserved.
//

import UIKit

/// 定义全局常量，尽量使用 private 修饰，否则到处都可以访问
private let cellId = "cellId"

class FGHomeViewController: FGBaseViewController {

    // 列表视图模型
    lazy var listViewModel = FGStatusListViewModel()
    
    /// 加载数据
    override func loadData() {
        
        print("准备刷新，最后一条 \(self.listViewModel.statusList.last?.status.text ?? "")")
        listViewModel.loadStatus(pullup: isPullup) { (isSuccess,shouldRefresh) in
            
            print("数据加载结束)")
            // 结束刷新控件
            self.refreshControl?.endRefreshing()
            // 恢复上拉刷新标记
            self.isPullup = false
            // 刷新表格
            if shouldRefresh {
                self.tableView?.reloadData()
            }
        }
    }
    
    // 显示好友
    @objc func showFriends() {
        
        let vc = FGDemoViewController()

        navigationController?.pushViewController(vc, animated: true)
    }
}

// MARK: - 表格数据方法
extension FGHomeViewController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listViewModel.statusList.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 1.取cell
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! FGStatusCell
        
        // 2.设置cell
        let viewModel = listViewModel.statusList[indexPath.row]
        cell.viewModel = viewModel
        
        // 3.返回cell
        return cell
    }
}

// MARK: - 设置界面
extension FGHomeViewController {
    
    // 重写父类方法
    override func setupTableView() {
        super.setupTableView()
        
        // 设置导航栏按钮
        navItem.leftBarButtonItem = UIBarButtonItem(title: "好友", target: self, action: #selector(showFriends))
        
        // 注册原型cell
        tableView?.register(UINib(nibName: "FGStatusNormalCell", bundle: nil), forCellReuseIdentifier: cellId)
        
        // 设置行高
        tableView?.rowHeight = UITableViewAutomaticDimension
        tableView?.estimatedRowHeight = 300
        
        // 取消分隔线
        tableView?.separatorStyle = .none
        
        setupNavTitle()
    }
    
    /// 设置导航栏标题
    func setupNavTitle() {
        
        let title = FGNetworkManager.shared.userAccount.screen_name
        
        let button = FGTitleButton(title: title)
        
        navItem.titleView = button
        button.addTarget(self, action: #selector(clickTitleButton), for: .touchUpInside)
    }
    
    @objc private func clickTitleButton(btn:UIButton) {
        // 选中状态
        btn.isSelected = !btn.isSelected
    }
}
